package cn.stronglink.assetmanage.business.check.view.detail;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import Scaner.rfid.IRfidListener;
import Scaner.rfid.TimerRfidScaner;
import Scaner.scan.IScanerListener;
import Scaner.scan.TimerInfraraedScaner;
import cn.stronglink.assetmanage.BuildConfig;
import cn.stronglink.assetmanage.R;
import cn.stronglink.assetmanage.business.check.model.CheckDetailModel;
import cn.stronglink.assetmanage.business.check.presenter.CheckDetailPresenter;
import cn.stronglink.assetmanage.business.inventory.model.InventoryDetailModel;
import cn.stronglink.assetmanage.business.inventory.model.InventoryModel;
import cn.stronglink.assetmanage.business.task.model.ITaskSyncListener;
import cn.stronglink.assetmanage.business.task.model.OrderType;
import cn.stronglink.assetmanage.business.task.model.TaskSyncModel;
import cn.stronglink.assetmanage.dao.DaoManager;
import cn.stronglink.assetmanage.dao.SyncTypesDao;
import cn.stronglink.assetmanage.entity.Asset;
import cn.stronglink.assetmanage.entity.Brand;
import cn.stronglink.assetmanage.entity.Check;
import cn.stronglink.assetmanage.entity.Department;
import cn.stronglink.assetmanage.entity.Model;
import cn.stronglink.assetmanage.entity.Node;
import cn.stronglink.assetmanage.entity.Room;
import cn.stronglink.assetmanage.entity.Type;
import cn.stronglink.assetmanage.entity.User;
import cn.stronglink.assetmanage.index.base.BaseChildFragment;
import cn.stronglink.assetmanage.utils.Constants;
import cn.stronglink.assetmanage.utils.ImageUtils;
import cn.stronglink.assetmanage.utils.SpinnerShowUtil;
import cn.stronglink.assetmanage.utils.ToastUtil;
import cn.stronglink.assetmanage.widget.MenuOrderDialog;
import util.StringUtils;

import static android.app.Activity.RESULT_CANCELED;
import static android.app.Activity.RESULT_OK;

/**
 * 入库验收详情
 */
public class WaitCheckDetailFragment extends BaseChildFragment implements View.OnClickListener, IScanerListener, ITaskSyncListener {
    private Spinner sp_check_location;
    private Spinner sp_brand_name;
    private Spinner sp_check_asset_class;
    private Spinner sp_check_model;
    private Asset asset;
    private CheckDetailModel checkDetailModel;
    private CheckDetailView checkDetailView;
    private CheckDetailPresenter checkDetailPresenter;
    private EditText tv_check_asset_name, tv_check_asset_no, tv_check_sn_no, tv_check_rfid_no;
    private ImageView iv_check_picture;
    public static final int PICTURE_URL = 5;
    private TimerInfraraedScaner scaner;
    private int ScanData = 0;
    TaskSyncModel taskSyncModel = null;
    private TextView txt_title_right, txt_title_left, txt_main_title;
    private Bitmap bitmap;
    private String brandId = "", typeId = "";
    private ArrayAdapter<Model> modelArrayAdapter;

    @Nullable
    @Override

    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_check_in_detail, container, false);
        initView(view);
        initData();
        return view;
    }

    private void initData() {
        List<Model> modelList = checkDetailPresenter.getModelList();
        List<Type> typeList = checkDetailPresenter.getTypeList();
        List<Brand> brandList = checkDetailPresenter.getBrandList();
        List<Room> roomList = checkDetailPresenter.getRoomList();
        modelArrayAdapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_dropdown_item_1line, modelList);
        ArrayAdapter<Type> typeArrayAdapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_dropdown_item_1line, typeList);
        ArrayAdapter<Brand> brandArrayAdapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_dropdown_item_1line, brandList);
        ArrayAdapter<Room> roomArrayAdapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_dropdown_item_1line, roomList);
        sp_check_location.setAdapter(roomArrayAdapter);
        sp_check_model.setAdapter(modelArrayAdapter);
        sp_brand_name.setAdapter(brandArrayAdapter);
        sp_check_asset_class.setAdapter(typeArrayAdapter);

        sp_check_model.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                Model model = (Model) sp_check_model.getSelectedItem();
                asset.setModelName(model.getName());
                asset.setModelId_(model.getId_());
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        sp_check_location.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                Room room = (Room) sp_check_location.getSelectedItem();
                asset.setRoomName(room.getName());
                asset.setRoomId_(room.getId_());
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        sp_brand_name.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                Brand brand = (Brand) sp_brand_name.getSelectedItem();
                brandId = brand.getId_();
                asset.setBrandName(brand.getName());
                asset.setBrandId_(brand.getId_());
                setModeData();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        sp_check_asset_class.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                Type type = (Type) sp_check_asset_class.getSelectedItem();
                typeId = type.getId_();
                asset.setTypeName(type.getName());
                asset.setTypeId_(type.getId_());
                setModeData();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        checkDetailPresenter.showDetailData(asset);
    }

    private void setModeData() {
        List<Model> modelList = checkDetailPresenter.queryModelByBrandAndType(brandId, typeId);
        if (modelList != null) {
            modelArrayAdapter.clear();
            modelArrayAdapter.addAll(modelList);
        }
    }

    protected Activity mActivity;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        this.mActivity = (Activity) context;
    }

    private void initView(View view) {
        txt_title_right = this.getActivity().findViewById(R.id.txt_right_title);
        txt_title_right.setVisibility(View.VISIBLE);
        txt_title_left = this.getActivity().findViewById(R.id.txt_left_title);
        txt_title_left.setVisibility(View.VISIBLE);
        txt_main_title = this.getActivity().findViewById(R.id.txt_main_title);
        txt_main_title.setText("待入库详情");
        asset = new Asset();
        sp_check_location = view.findViewById(R.id.sp_check_location);
        sp_brand_name = view.findViewById(R.id.sp_brand_name);
        sp_check_asset_class = view.findViewById(R.id.sp_check_asset_class);
        sp_check_model = view.findViewById(R.id.sp_check_model);
        tv_check_asset_no = view.findViewById(R.id.tv_check_asset_no);
        tv_check_sn_no = view.findViewById(R.id.tv_check_sn_no);
        tv_check_rfid_no = view.findViewById(R.id.tv_check_rfid_no);
        iv_check_picture = view.findViewById(R.id.iv_check_picture);
        tv_check_asset_no.setOnClickListener(this);
        tv_check_sn_no.setOnClickListener(this);
        tv_check_rfid_no.setOnClickListener(this);
        iv_check_picture.setOnClickListener(this);
        txt_title_left.setOnClickListener(this);
        txt_title_right.setOnClickListener(this);
        checkDetailModel = new CheckDetailModel();
        taskSyncModel = new TaskSyncModel();
        taskSyncModel.setListener(this);
        checkDetailView = new CheckDetailView(this, view);
        checkDetailPresenter = new CheckDetailPresenter(checkDetailModel, checkDetailView);
        Bundle bundle = getArguments();
        if (bundle != null) {
            long asset_id = bundle.getLong(Constants.CHECK_IN_DETAIL_NO);
            asset = checkDetailModel.getAssetById(asset_id);

        } else {
            checkDetailView.showToast(getString(R.string.get_no_data));
        }


        this.scaner = new TimerInfraraedScaner(this.getContext());
        this.scaner.setScanerListener(this);
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (scaner != null) {
            this.scaner.stop();
            this.scaner.destory();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_check_asset_no:
                // 资产编号扫描
                ScanData = 1;
                scaner.playSingle();
                break;
            case R.id.tv_check_sn_no:
                //sn号扫描
                ScanData = 2;
                scaner.playSingle();
                break;
            case R.id.tv_check_rfid_no:
                // rfid扫描
                ScanData = 3;
                scaner.playSingle();
                break;
            case R.id.iv_check_picture:
                checkDetailView.startActivityForPicture(PICTURE_URL);
                break;
            case R.id.txt_left_title:
                //返回
//                checkDetailView.backWaitCheckAssetFragment(asset);
                mActivity.onBackPressed();
                break;
            case R.id.txt_right_title:
                //保存详情,资产编号和sn为必填项
                if (tv_check_sn_no.getText().toString().isEmpty()) {
                    ToastUtil.toastShort("SN号不能为空");
                    return;
                }
                if (tv_check_asset_no.getText().toString().isEmpty()) {
                    ToastUtil.toastShort("资产编号不能为空");
                    return;
                }
                if (asset != null) {
                    asset.setIsUpdate(true);
                    asset.setAssetNo(StringUtils.replaceBlank(tv_check_asset_no.getText().toString()));
                    asset.setRfidNo(StringUtils.replaceBlank(tv_check_rfid_no.getText().toString()));
                    asset.setSerialNo(StringUtils.replaceBlank(tv_check_sn_no.getText().toString()));
                    String time = new SimpleDateFormat("yyyy-MM-dd hh:MM:ss").format(new Date());
                    asset.setUpdateTime(time);
                    asset.setUpdateBy(Long.valueOf(User.getInstance().getId_()));
                    if (bitmap != null) {
                        // 之前本地有图片先删除
                        if (asset.getPictureUri() != null && !asset.getPictureUri().isEmpty()) {
                            ImageUtils.deleteImage(asset.getPictureUri());
                        }
                        // 保存图片到本地
                        String path = ImageUtils.saveImageToLocal(bitmap);
                        asset.setPictureUri(path);
                    }
                    checkDetailPresenter.saveDetailData(asset);
                    checkDetailView.showToast("保存成功");
                    mActivity.onBackPressed();
                }

                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (resultCode) {
            case RESULT_OK:
                switch (requestCode) {
                    case PICTURE_URL:
                        Bundle bundle = data.getExtras();
                        if (bundle != null) {
                            bitmap = (Bitmap) bundle.get("data");// 获取相机返回的数据，并转换为Bitmap图片格式
                            checkDetailView.showAssetPicture(bitmap);
                        } else {
                            checkDetailView.showToast("没有图片");
                        }
                        break;
                }

                break;
            case RESULT_CANCELED:

                break;
        }
    }


    @Override
    public void onScaning(List<String> data) {
        final String resultData = data.get(data.size() - 1).replace(" ", "");
        switch (ScanData) {
            case 1:
                //资产编号
                tv_check_asset_no.setText(resultData);
                if (asset != null) {
                    asset.setAssetNo(tv_check_asset_no.getText().toString());
                }
                break;
            case 2:
                //sn
                tv_check_sn_no.setText(resultData);
                if (asset != null) {
                    asset.setSerialNo(tv_check_sn_no.getText().toString());
                }
                break;
            case 3:
                //todo 显示扫描到的rfid数据
//                if (resultData != null) {
//                    if (resultData != null && mActivity != null) {
//                        mActivity.runOnUiThread(new Runnable() {
//                            @Override
//                            public void run() {
//                                showScanRfidDialog(resultData);
//                            }
//                        });
//                    }
//                }
                //rfid
                tv_check_rfid_no.setText(resultData);
                if (asset != null) {
                    asset.setRfidNo(tv_check_rfid_no.getText().toString());
                }
                break;
        }


    }

    private void showScanRfidDialog(String resultData) {
        AlertDialog.Builder builder = new AlertDialog.Builder(mActivity);
        builder.setMessage("扫描到的rfid:" + resultData + "\n" + "rfid的长度为：" + resultData.length()
                + "\n" + "应用版本:" + BuildConfig.VERSION_CODE);
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.create();
        builder.show();
    }


    @Override
    public void onFail(String orderNo, OrderType orderType, Exception e, int sum) {
        //同步失败
        checkDetailView.hideProgressDialog();
        checkDetailView.showToast(getString(R.string.sync_data_fail));
    }

    @Override
    public void onSucces(String orderNo, OrderType orderType, int sum) {
        //同步成功
        checkDetailView.hideProgressDialog();
        checkDetailView.showToast(getString(R.string.check_sync_ok));
        checkDetailModel.deleteSyncData();
    }
}
